package com.itlong.cloud.controller.sdkV1.old.appClient;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.itlong.cloud.POJO.DTO.app.old.AppOldUserInfoDto;
import com.itlong.cloud.POJO.VO.app.old.AppOldAdVo;
import com.itlong.cloud.POJO.VO.app.old.AppOldDeviceVO;
import com.itlong.cloud.POJO.VO.app.old.AppOldPushVO;
import com.itlong.cloud.POJO.VO.property.PropertyEquipAddressVO;
import com.itlong.cloud.POJO.VO.property.PropertyProjectUnitSimpleInfoVO;
import com.itlong.cloud.POJO.VO.sdk.old.SDKAppOldDeviceVO;
import com.itlong.cloud.POJO.VO.sdk.old.SDKAppOldUserInfoCacheVO;
import com.itlong.cloud.POJO.VO.sdk.old.SDKAppOldUserInfoVO;
import com.itlong.cloud.enumerate.oldapp.Code;
import com.itlong.cloud.enumerate.oldapp.Message;
import com.itlong.cloud.equip.property.IPropertyEquipServiceClient;
import com.itlong.cloud.user.app.IAppOldHomeServiceClient;
import com.itlong.cloud.user.app.IAppOldMineServiceClient;
import com.itlong.cloud.user.app.IAppOldRegisterServiceClient;
import com.itlong.cloud.user.sdk.ISDKAppOldUserServiceClient;
import com.itlong.cloud.utils.random.RandomUtil;
import com.itlong.cloud.utils.words.StringHandlerUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

/**
 * <desc>
 *      SDKApp端用户信息Controller
 * </desc>
 *
 * @createDate 2017/10/26
 */
@RestController
@RequestMapping("/jiabanjing/interface")
public class SDKAppOldUserContorller {

    //日志记录对象
    private static final Logger LOG = LoggerFactory.getLogger(SDKAppOldUserContorller.class);

    @Autowired
    ISDKAppOldUserServiceClient isdkAppOldUserServiceClient; //旧版APP_SDK用户服务暴露层接口

    @Autowired
    IAppOldMineServiceClient iAppOldMineServiceClient;

    @Autowired
    IAppOldHomeServiceClient iAppOldHomeService;

    @Autowired
    IAppOldRegisterServiceClient iAppOldRegisterServiceClient;

    @Autowired
    IPropertyEquipServiceClient iPropertyEquipServiceClient;

    /**
     * <desc>
     *    获取SDK APP用户信息.
     * </desc>
     *
     * @param appid 应用接入凭证
     * @param phoneNo 用户手机号
     * @return 标准格式化响应结果
     * @author LewisLouis
     * @createDate 2017-11-06
     */
    @ResponseBody
    @RequestMapping(path = "/app/getUserInfo")
    public Message getSDKAppUserInfo(String appid, String phoneNo){
        try {
            //尝试从缓存中取出用户信息（若get到，则get时底层会自动延期）
            SDKAppOldUserInfoCacheVO sdkAppCacheUser = isdkAppOldUserServiceClient.getSDKAppCacheUser(appid, phoneNo);
            if ((null == sdkAppCacheUser) ||(StringUtils.isEmpty(sdkAppCacheUser.getToken()))){
                return new Message(Code.TOKEN_ERR);
            }

            List<String> projectIds = isdkAppOldUserServiceClient.getProjectInfos(phoneNo,appid);
            if ((projectIds == null) || projectIds.isEmpty()){
                return new Message(Code.NOT_FOUNDUSER);
            }

            SDKAppOldUserInfoVO sdkAppOldUserInfoVO = new SDKAppOldUserInfoVO();
            //获取其中一个所在房间的户主的手机号码
            String parentPhoneNo = isdkAppOldUserServiceClient.getOneParentPhoneNoByUserId(sdkAppCacheUser.getUserId());
            sdkAppOldUserInfoVO.setParentPhonetNo(parentPhoneNo);

            //从缓存中获取用户信息（部分基本无变化的信息）
            getUserInfoFromCache(sdkAppOldUserInfoVO,sdkAppCacheUser);

            //从数据获取用户-项目信息（部分可能会变化的信息）
            getUserProjectInfosFromDB(sdkAppOldUserInfoVO,projectIds);

            return new Message(Code.SUCCESS,sdkAppOldUserInfoVO);
        } catch (Exception e) {
            LOG.error(String.format("【SDK_APP_获取用户信息】{appid:%s phoneNo:%s} exception:{%s}", appid,phoneNo,e));
            return new Message(Code.ERROR);
        }
    }


    /**
     * <desc>
     *    获取SDK APP用户信息.
     * </desc>
     *
     * @param appid 应用接入凭证
     * @param phoneNo 用户手机号
     * @return 标准格式化响应结果
     * @author LewisLouis
     * @createDate 2017-11-06
     */
    @ResponseBody
    @RequestMapping(path = "/app/open")
    public Message appOpen(String pushAutoIndex, String phoneNo, String appid, Integer pageSize, Integer pageNo){
        try {
            //尝试从缓存中取出用户信息（若get到，则get时底层会自动延期）
            SDKAppOldUserInfoCacheVO sdkAppCacheUser = isdkAppOldUserServiceClient.getSDKAppCacheUser(appid, phoneNo);
            if ((null == sdkAppCacheUser) ||(StringUtils.isEmpty(sdkAppCacheUser.getToken()))){
                return new Message(Code.TOKEN_ERR);
            }

            JSONObject data = new JSONObject();
            AppOldUserInfoDto appOldUserInfoDto = iAppOldRegisterServiceClient.selectDtoByPhone(phoneNo);
            if (appOldUserInfoDto == null){
                return  new Message(Code.TOKEN_ERR);
            }
            String projectId  = "";
            String userId = appOldUserInfoDto.getUserId();

            //获取推送消息
            if (null == pushAutoIndex){
                pushAutoIndex = "";
            }
            AppOldPushVO appOldPushVO = iAppOldHomeService.getAppOldPushVO(appOldUserInfoDto.getUserId(),pushAutoIndex,projectId);
            data.put("pushInfo",appOldPushVO);
            //获取广告信息
            List<AppOldAdVo> adsArr = iAppOldHomeService.getAppOldAd(appOldUserInfoDto.getUserId(),projectId);
            data.put("ads",adsArr);

            //获取用户项目列表及各项目的设备权限信息
            JSONArray userProjectArr = new JSONArray();
            //查询用户拥有的项目列表
            Map<String,Object> projectparam = new HashMap<>();
            projectparam.put("userId",appOldUserInfoDto.getUserId());
            if (StringUtils.isNotBlank(projectId)){
                projectparam.put("projectId",projectId);
            }

            //获取手机号拥有的AppId绑定到项目
            List<String> projectIdsBindAppId = isdkAppOldUserServiceClient.getProjectInfos(phoneNo,appid);
            if ((projectIdsBindAppId == null) || projectIdsBindAppId.isEmpty()){
                return new Message(Code.NOT_FOUNDUSER);
            }

            List<Map<String,Object>> userProjectList = iAppOldHomeService.getUserProject(appOldUserInfoDto.getUserId(),projectId);

            if (userProjectList != null && userProjectList.size() > 0){
                String cardNum = "000000",pubKey = "";
                for (Map userprojectmap : userProjectList){
                    String currentProjectId = userprojectmap.get("projectId").toString();
                    if (!projectIdsBindAppId.contains(currentProjectId)){
                        //不在当前AppID管理下的项目不展示
                        continue;
                    }
                    JSONObject uprjs = new JSONObject();
                    uprjs.put("projectId",currentProjectId);
                    uprjs.put("projectName",userprojectmap.get("projectName").toString());
                    uprjs.put("userTypeInProject",userprojectmap.get("userType").toString());
                    pubKey = userprojectmap.get("pubKey").toString();
                    uprjs.put("pubKey",pubKey);
                    uprjs.put("valiTime", "");
                    if (userprojectmap.containsKey("cardNum") && userprojectmap.get("cardNum") != null
                            && StringUtils.isNotBlank(userprojectmap.get("cardNum").toString())){
                        cardNum = userprojectmap.get("cardNum").toString();
                    }
                    uprjs.put("cardNum",cardNum);


                    List<AppOldDeviceVO> wholeDeviceAuthList = new ArrayList<>();

                    //查询用户门禁设备列表
                    List<AppOldDeviceVO> entranceAuthList = iAppOldHomeService.getUserEntranceAuthList(
                            userId,currentProjectId,pageNo.toString(),pageSize.toString(),cardNum,pubKey);

                    wholeDeviceAuthList.addAll(entranceAuthList);
                    //查询电梯设备列表
                    List<AppOldDeviceVO> elevatorAuthList = iAppOldHomeService.getUserElevatorAuthList(
                            userId,currentProjectId,pageNo.toString(),pageSize.toString(),cardNum,pubKey);

                    wholeDeviceAuthList.addAll(elevatorAuthList);


                    //获取设备的服务地址
                    List<SDKAppOldDeviceVO> sdkAppOldDeviceVOS =  this.getDeviceInfos(wholeDeviceAuthList,currentProjectId);

                    //添加用户在项目中的权限设备集合
                    uprjs.put("deviceinfoArr",sdkAppOldDeviceVOS);
                    userProjectArr.add(uprjs);
                }
            }
            data.put("deviceInfos", userProjectArr);
            return new Message(Code.SUCCESS, data);
        } catch (Exception e) {
            LOG.error(String.format("【SDK_APP_获取主页信息】{appid:%s phoneNo:%s} exception:{%s}", appid,phoneNo,e));
            return new Message(Code.ERROR);
        }
    }

    /**
    * <desc>
    *    从缓存中获取用户信息（部分基本无变化的信息）.
    * </desc>
    *
    * @param sdkAppOldUserInfoVO 待返回出去的用户信息
     * @params dkAppCacheUser 缓存中的用户信息
    * @author LewisLouis
    * @createDate 2017-11-15
    */
    private void getUserInfoFromCache(SDKAppOldUserInfoVO sdkAppOldUserInfoVO, SDKAppOldUserInfoCacheVO sdkAppCacheUser){
        sdkAppOldUserInfoVO.setUserId(sdkAppCacheUser.getUserId());
        sdkAppOldUserInfoVO.setAppid(sdkAppCacheUser.getAppid());
        sdkAppOldUserInfoVO.setUserName(sdkAppCacheUser.getUserName());
        sdkAppOldUserInfoVO.setToken(sdkAppCacheUser.getToken());
        sdkAppOldUserInfoVO.setInvalidTime(sdkAppCacheUser.getInvalidTime());
        sdkAppOldUserInfoVO.setCreateTime(sdkAppCacheUser.getCreateTime());
        sdkAppOldUserInfoVO.setExpiresIn(sdkAppCacheUser.getExpiresIn());
        sdkAppOldUserInfoVO.setPhoneNo(sdkAppCacheUser.getPhoneNo());
        sdkAppOldUserInfoVO.setUserType(1);
    }

    /**
     * <desc>
     *    从数据获取用户-项目信息（部分可能会变化的信息）
     * </desc>
     *
     * @param sdkAppOldUserInfoVO 待返回出去的用户信息
     * @author LewisLouis
     * @createDate 2017-11-15
     */
    private void getUserProjectInfosFromDB(SDKAppOldUserInfoVO sdkAppOldUserInfoVO,List<String> projectIdsBindAppId){
        JSONObject projectJS = isdkAppOldUserServiceClient.getUserProjectInfo(sdkAppOldUserInfoVO.getUserId(),"");
        String allProjectIds = projectJS.getString("projectIds");
        String allProjectNames = projectJS.getString("projectNames");
        String allUserTypeInProject = projectJS.getString("userTypeInProject");
        String allPubKeys = projectJS.getString("pubKeys");
        String allUserAuth = projectJS.getString("userAuth");
        List<String>  allProjectIdList = Arrays.asList(allProjectIds.split(","));
        List<String> sortNums = new ArrayList<>();

        //手机用户所有项目中不在AppId下的项目信息需要被移除，先找出项目数据索引
        List<Integer> needRemoveProjectDataIndexs = new ArrayList<>();
        for (int projectDataIndex = 0;projectDataIndex < allProjectIdList.size(); projectDataIndex ++){
            String oneProjectId = allProjectIdList.get(projectDataIndex);
            if (projectIdsBindAppId.indexOf(oneProjectId) < 0) {
                needRemoveProjectDataIndexs.add(projectDataIndex);
            } else {
                sortNums.add(String.valueOf(RandomUtil.getRandomAround(8,1)));
            }

        }

        for (int index = needRemoveProjectDataIndexs.size() - 1;index >= 0 ; index --){
            int needRemoveProjectDataIndex = needRemoveProjectDataIndexs.get(index);
            allProjectIds = removeProjectDataByIndex(needRemoveProjectDataIndex,allProjectIds);
            allProjectNames = removeProjectDataByIndex(needRemoveProjectDataIndex,allProjectNames);
            allUserTypeInProject = removeProjectDataByIndex(needRemoveProjectDataIndex,allUserTypeInProject);
            allPubKeys =  removeProjectDataByIndex(needRemoveProjectDataIndex,allPubKeys);
            allUserAuth = removeProjectDataByIndex(needRemoveProjectDataIndex,allUserAuth);
        }

        sdkAppOldUserInfoVO.setProjectIds(allProjectIds);
        sdkAppOldUserInfoVO.setProjectNames(allProjectNames);
        sdkAppOldUserInfoVO.setUserTypeInProject(allUserTypeInProject);
        sdkAppOldUserInfoVO.setPubKeys(allPubKeys);
        sdkAppOldUserInfoVO.setUserAuth(allUserAuth);
        sdkAppOldUserInfoVO.setUserSortNum(StringUtils.join(sortNums, ","));
    }

    /**
    * <desc>
    *    移除指定索引到项目信息.
    * </desc>
    *
    * @param  * @param null
    * @return xx
    * @author LewisLouis
    * @createDate 2018-02-26
    */
    private String removeProjectDataByIndex(int projectIndex,String oldProjectDatas){
        if (StringUtils.isBlank(oldProjectDatas)){
            return oldProjectDatas;
        }
        List<String> oldProjectDataList = StringHandlerUtil.splitStringList(oldProjectDatas);
        if (oldProjectDataList.isEmpty() || oldProjectDataList.size() <= projectIndex ){
            return oldProjectDatas;
        }
        oldProjectDataList.remove(projectIndex);
        return StringUtils.join(oldProjectDataList,",");

    }


    /**
    * <desc>
    *     获取每个设备的其它信息（如服务的地址,项目）
    * </desc>
    *
    * @param  appOldDeviceVOS 设备列表
    * @author LewisLouis
    * @createDate 2017-12-05
    */
    private List<SDKAppOldDeviceVO> getDeviceInfos(List<AppOldDeviceVO> appOldDeviceVOS, String projectId){
        List<SDKAppOldDeviceVO> sdkAppOldDeviceVOS = new ArrayList<>();
        for (AppOldDeviceVO oldDeviceVO:appOldDeviceVOS){
            oldDeviceVO.setProjectId(projectId);

            List<PropertyEquipAddressVO> propertyEquipAddressVOS = iPropertyEquipServiceClient.getEquipAddress(oldDeviceVO.getDeviceUnique());
            if ((null != propertyEquipAddressVOS) && (!propertyEquipAddressVOS.isEmpty())){
                StringBuffer buildNumsOneDevice = new StringBuffer();
                StringBuffer unitNumsOneDevice = new StringBuffer();
                for (PropertyEquipAddressVO propertyEquipAddressVO:propertyEquipAddressVOS){
                    if (buildNumsOneDevice.length() > 0){
                        buildNumsOneDevice.append(",");
                    }
                    if (unitNumsOneDevice.length() > 0){
                        unitNumsOneDevice.append(";");
                    }
                    buildNumsOneDevice.append(propertyEquipAddressVO.getBuildNum());
                    List<PropertyProjectUnitSimpleInfoVO> propertyProjectUnitSimpleInfoVOS = propertyEquipAddressVO.getUnits();
                    StringBuffer unitNumsOneBuild = new StringBuffer();
                    for (PropertyProjectUnitSimpleInfoVO propertyProjectUnitSimpleInfoVO:propertyProjectUnitSimpleInfoVOS){
                        if (unitNumsOneBuild.length() > 0){
                            unitNumsOneBuild.append(",");
                        }
                        unitNumsOneBuild.append(propertyProjectUnitSimpleInfoVO.getUnitNum());
                    }
                    unitNumsOneDevice.append(unitNumsOneBuild.toString());
                }
                oldDeviceVO.setOwnBuildNum(buildNumsOneDevice.toString());
                oldDeviceVO.setOwnUnitNum(unitNumsOneDevice.toString());
            }

            SDKAppOldDeviceVO sdkAppOldDeviceVO = new SDKAppOldDeviceVO();
            BeanUtils.copyProperties(oldDeviceVO,sdkAppOldDeviceVO);
            sdkAppOldDeviceVO.setValiTime(oldDeviceVO.getValiTime());

            sdkAppOldDeviceVO = (SDKAppOldDeviceVO)StringHandlerUtil.formatString(sdkAppOldDeviceVO);
            sdkAppOldDeviceVOS.add(sdkAppOldDeviceVO);

        }

        return sdkAppOldDeviceVOS;
    }


}
